package git.soulbgm.socket;

import git.soulbgm.utils.ChannelUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;

import java.net.InetSocketAddress;

/**
 * TCP客户端处理数据类
 *
 * @author SoulBGM
 * @date 2021-03-29
 */
@ChannelHandler.Sharable
public class TcpClientHandle extends SimpleChannelInboundHandler<ByteBuf> {

    private TcpClient tcpClient;

    /**
     * 是否连接重试
     */
    private boolean retry;

    public TcpClientHandle() {
        tcpClient = TcpClient.getClient();
        this.retry = true;
    }

    /**
     * 用户事件触发
     *
     * @param ctx ctx
     * @param evt evt
     * @throws Exception 异常
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        /*if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (IdleState.READER_IDLE.equals(event.state())) {
                // 长期未收到服务端推送的消息
                // 可以选择重新连接
//                tcpClient.connect();
            } else if (IdleState.WRITER_IDLE.equals(event.state())) {
                // 长期未向服务端推送消息
                // 发送心跳包
//                ctx.channel().writeAndFlush(ByteUtil.stringToByteBuf("111222333$_$"));
            } else if (IdleState.ALL_IDLE.equals(event.state())) {
                // 长期未收到服务端推送的消息并且也长期未向服务端推送消息
            }
        }*/
    }

    /**
     * 当客户端连接时调用
     *
     * @param ctx 通道处理程序上下文
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    /**
     * 当客户端连接断开时调用
     *
     * @param ctx 通道处理程序上下文
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        Channel channel = ctx.channel();
        InetSocketAddress address = (InetSocketAddress) channel.remoteAddress();
        String ip = address.getAddress().getHostAddress();
        int port = address.getPort();
        ChannelUtil.removeChannelFuture(ip, port);
        if (retry) {
            connectionRetry(ip, port);
        }
    }

    /**
     * 连接重试
     *
     * @param ip   地址
     * @param port 端口
     */
    private void connectionRetry(String ip, int port) {
        tcpClient.log.warn("IP:{}, 端口:{} 连接断开，正在连接重试~~", ip, port);
        tcpClient.connect(ip, port, ChannelUtil.getChannelFutureListener(ip, port));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {

    }


}
